<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class OrderPayment extends Model
{
    const PAYMENT_STATUS_PENDING = "pending";
    const PAYMENT_STATUS_SUCCESS = "success";
    const PAYMENT_STATUS_CLOSED = "closed";

    const paymentStatusMap = [
      self::PAYMENT_STATUS_PENDING=>"待支付",
      self::PAYMENT_STATUS_SUCCESS=>"已支付",
      self::PAYMENT_STATUS_CLOSED=>"已关闭",
    ];

    public $table = "order_payments";
    protected $guarded = [];

    protected static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub
        // 监听模型创建事件，在写入数据库之前触发
        static::creating(function ($model) {
            // 如果模型的 pay_no 字段为空
            if (!$model->no) {
                // 调用 findAvailableNo 生成订单流水号
                $model->no = static::findAvailableNo();
                // 如果生成失败，则终止创建订单
                if (!$model->no) {
                    return false;
                }
            }
        });
    }

    public function order()
    {
        return $this->belongsTo(Order::class,"order_id");
    }

    public static function findAvailableNo()
    {
        // 支付流水号前缀
        $prefix ="P".date('YmdHis');
        for ($i = 0; $i < 10; $i++) {
            // 随机生成 6 位的数字
            $no = $prefix.str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT);
            // 判断是否已经存在
            if (!static::query()->where('no', $no)->exists()) {
                return $no;
            }
        }
        return false;
    }
}
